<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind" @submit="submit">
			<uni-forms-item name="name" label="商品名称" required>
				<uni-easyinput v-model="formData.name" :clearable="false" placeholder="请输入商品名称" />
			</uni-forms-item>
			<uni-forms-item name="goods_desc" label="商品描述" required>
				<uni-easyinput v-model="formData.goods_desc" :clearable="false" placeholder="请输入商品描述" />
			</uni-forms-item>
			<uni-forms-item name="goods_thumb" label="缩略图" required>
				<uni-file-picker
					v-model="uploadFiles"
					fileMediatype="image" 
					mode="grid"
					return-type="object"
					@select="selectFile" 
					@success="uploadSucc" 
					@fail="uploadFail" 
					@delete="deleteFile"
				/>
			</uni-forms-item>
			<uni-forms-item name="goods_banner_imgs" label="商品图" required>
				<uni-file-picker
					v-model="uploadBannerFiles"
					fileMediatype="image" 
					mode="grid"
					return-type="array"
					@select="selectFile" 
					@success="uploadBannerSucc" 
					@fail="uploadFail" 
					@delete="deleteBannerFile"
				/>
			</uni-forms-item>
			<uni-forms-item name="remain_count" label="商品库存" required>
				<uni-number-box v-model="formData.remain_count" max="10000"></uni-number-box>
			</uni-forms-item>
			<uni-forms-item name="seller_note" label="商家备注">
				<uni-easyinput v-model="formData.seller_note" :clearable="false" placeholder="请输入商家备注" />
			</uni-forms-item>
			<uni-forms-item name="is_on_sale" label="是否上架">
				<switch @change="bindFormData('is_on_sale', $event.detail.value)" :checked="formData.is_on_sale" />
			</uni-forms-item>
			<uni-forms-item name="add_date" label="上架时间">
				<uni-datetime-picker :value="formData.add_date" return-type="timestamp" :disabled="!formData.is_on_sale" @change="changeDate" />
			</uni-forms-item>
			<uni-forms-item name="is_best" label="是否精品">
				<switch @change="bindFormData('is_best', $event.detail.value)" :checked="formData.is_best" />
			</uni-forms-item>
			<uni-forms-item name="is_new" label="是否新品">
				<switch @change="bindFormData('is_new', $event.detail.value)" :checked="formData.is_new" />
			</uni-forms-item>
			<uni-forms-item name="is_hot" label="是否热销">
				<switch @change="bindFormData('is_hot', $event.detail.value)" :checked="formData.is_hot" />
			</uni-forms-item>
			<view class="uni-button-group">
				<button style="width: 100px;" type="primary" class="uni-button"
					@click="submitForm">{{$t('common.button.submit')}}</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button style="width: 100px;"
						class="uni-button">{{$t('common.button.back')}}</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/opendb-mall-goods.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'opendb-mall-goods';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			return {
				formData: {
					"name": "",
					"goods_desc": "",
					"seller_note":"",
					"remain_count":0,
					"add_date":"",
					"goods_thumb":"",
					"goods_banner_imgs":[],
					"is_on_sale":false,
					"is_best":false,
					"is_new":false,
					"is_hot":false
				},
				formDataId:'',
				uploadFiles:[],
				uploadBannerFiles:[],
				rules: {
					...getValidator(["name", "goods_desc", "seller_note", "remain_count", "is_on_sale","is_best","is_new","is_hot","add_date"])
				}
			}
		},
		onLoad(e) {
			const id = e.id
			this.formDataId = id
			this.getDetail(id)
		},
		methods: {
			changeDate(val){
				this.bindFormData('add_date',val)
			},
			getDetail(id){
				uniCloud.callFunction({
					name: 'shop-api',
					data: {
						action: 'goods/getOne',
						data:{
							id
						}
					}
				}).then(({result}) =>{
					if(result.code==200){
						result.data.id=result.data._id;
						delete result.data._id;
						//result.data.add_date=this.$formatDate(result.data.add_date,'yyyy-MM-dd hh:mm:ss');
						Object.assign(this.formData,result.data);
						if(this.formData.goods_thumb){
							this.uploadFiles=[{
								"name":"file.txt",
								"extname":"txt",
								"url":this.formData.goods_thumb
							}]
						}
						if(this.formData.goods_banner_imgs.length>0){
							this.uploadBannerFiles=this.formData.goods_banner_imgs.map(item => {
								return {
									"name":"file.txt",
									"extname":"txt",
									"url":item
								}
							})
						}
						console.log(this.formData,result)
					}
				})
			},
			// 上传成功
			uploadSucc(e){
				console.log('上传成功',e,this.uploadFiles)
				this.bindFormData('goods_thumb',this.uploadFiles.url)
			},
			uploadBannerSucc(e){
				this.formData.goods_banner_imgs.push(e.tempFilePaths)
				console.log('上传成功',e,this.formData.goods_banner_imgs)
			},
			// 上传失败
			uploadFail(e){
				console.log('上传失败：',e)
			},
			deleteFile(e){
				console.log('删除文件：',e)
				this.bindFormData('icon','')
			},
			deleteBannerFile(e){
				const idx=this.formData.goods_banner_imgs.indexOf(e.tempFilePath)
				this.formData.goods_banner_imgs.splice(idx,1)
				console.log('删除文件：',e)
			},
			selectFile(e){
				console.log('选择文件：',e)
			},
			bindFormData(name,val){
				this.$refs['form'].setValue(name,val);
				this.formData[name]=val;
			},
			/**
			 * 触发表单提交
			 */
			submitForm() {
				this.$refs.form.submit();
			},

			/**
			 * 表单提交
			 * @param {Object} event 回调参数 Function(callback:{value,errors})
			 */
			submit(event) {
				const {
					value,
					errors
				} = event.detail

				// 表单校验失败页面会提示报错 ，要停止表单提交逻辑
				if (errors) {
					return
				}
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				// 是否启用功能的数据类型转换， 0 正常， 1 禁用
				if (typeof value.status === "boolean") {
					value.status = Number(!value.status)
				}
				uniCloud.callFunction({
					name: 'shop-api',
					data: {
						action: 'goods/edit',
						data:this.formData
					}
				}).then(({result}) =>{
					uni.hideLoading();
					if(result.code==200){
						uni.showToast({
						  title: '修改成功'
						})
						uni.navigateTo({
							url:'./list'
						})
					}else{
						uni.showToast({
						  title: result.message
						})
					}
				})
			}
		}
	}
</script>
<style>
	::v-deep .uni-forms-item__label {
		width: 90px !important;
	}
</style>
